package com.kaifamiao.reqeust;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Collection;

@WebServlet("/form/data")
@MultipartConfig
public class FormDataServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        throw new ServletException( "不支持以GET方式提交`multipart/form-data`" );
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 只有为 `servlet` 设置了 `multipart config` 才可以使用 getParts 和 getPart 方法
        Collection<Part> parts = request.getParts();

        response.setCharacterEncoding( "UTF-8" );
        response.setContentType( "text/html; charset=UTF-8" );
        PrintWriter out = response.getWriter();

        for ( Part p : parts ) {
            System.out.println( p );
            String cd = p.getHeader( "content-disposition" );
            System.out.println( cd );
            // 获得表单控件的名称，比如 <input type="text" name="realName">
            String name = p.getName(); // 可以获得 表单控件 中 name 属性的值
            InputStream in = p.getInputStream();
            byte[] bytes = in.readAllBytes();
            String value = new String( bytes, StandardCharsets.UTF_8 );
            out.printf( "<p>%s: %s</p>\n", name, value );
        }
    }
}
